package com.sqlcheck.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.CorsConfigurationSource;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    
    @Autowired
    private AppProperties appProperties;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        AppProperties.Security.Cors corsConfig = appProperties.getSecurity().getCors();
        
        registry.addMapping("/api/**")
            .allowedOriginPatterns(corsConfig.getAllowedOrigins().toArray(new String[0]))
            .allowedMethods(corsConfig.getAllowedMethods().toArray(new String[0]))
            .allowedHeaders(corsConfig.getAllowedHeaders().toArray(new String[0]))
            .allowCredentials(corsConfig.isAllowCredentials())
            .maxAge(corsConfig.getMaxAge());
    }

    @Bean
    public CorsConfigurationSource corsConfigurationSource() {
        AppProperties.Security.Cors corsConfig = appProperties.getSecurity().getCors();
        
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowedOriginPatterns(corsConfig.getAllowedOrigins());
        configuration.setAllowedMethods(corsConfig.getAllowedMethods());
        configuration.setAllowedHeaders(corsConfig.getAllowedHeaders());
        configuration.setAllowCredentials(corsConfig.isAllowCredentials());
        configuration.setMaxAge(corsConfig.getMaxAge());

        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/api/**", configuration);
        return source;
    }
}